package com.atomikos1.config;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import com.atomikos1.config.dataproperties.DataSource2Properties;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;
import javax.transaction.UserTransaction;
import java.util.Properties;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/24  13:46
 * 描述:
 */
@Configuration
@MapperScan(basePackages = {"com.atomikos1.mapper.dao2"},sqlSessionFactoryRef="sqlSessionFactory2")
public class DataSource2Config {

    @Bean("dataSource2")
    public DataSource getDataSource1(DataSource2Properties dataSource2Properties){
        Properties xaProperties=new Properties();
        xaProperties.put("url",dataSource2Properties.getUrl());
        xaProperties.put("username",dataSource2Properties.getUsername());
        xaProperties.put("password",dataSource2Properties.getPassword());

        AtomikosDataSourceBean atomikosDataSourceBean=new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
        atomikosDataSourceBean.setUniqueResourceName("manger6");
        atomikosDataSourceBean.setPoolSize(5);
        atomikosDataSourceBean.setXaProperties(xaProperties);

        return atomikosDataSourceBean;
    }


    /**
     * 作者: LCG
     * 日期: 2021/3/31  13:44
     * 描述: atomikos事务管理器
     * @Param []
     * @Return org.springframework.transaction.jta.JtaTransactionManager
     */
    @Bean("transactionManager")
    public JtaTransactionManager getDataSourceTransactionManager1(){

        UserTransactionManager userTransactionManager = new UserTransactionManager();
        UserTransaction userTransaction = new UserTransactionImp();
        return new JtaTransactionManager(userTransaction, userTransactionManager);


    }

    @Bean("sqlSessionFactory2")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:/mapper/db2/*.xml"));

        return sqlSessionFactoryBean.getObject();

    }

}
